package imlayer

import (
    "fmt"
	"encoding/json"
	"dhfshop/models/isv"
    "dhfshop/utils/helper"
	"dhfshop/models/im"
	"dhfshop/models/member"
	"dhfshop/service/redisgo"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"wxsdk/miniapp/message/custom/miniapp"
	"wxsdk/oauth"
)

func ForwardScanEvent(msg *im.WxMsgReceiptRecords, eventKey string) error {
    redisconn := redisgo.GetInstance()
	if msg.AppId == "wx204da65aa7d948b0" {
	    //beego.Debug("scan eventkey:", eventKey)
		if prefixCode := helper.Substr(eventKey,0,4); prefixCode == "1100" {
			if _, err := member.GetMemberByOpenId(msg.FromUserName); err == orm.ErrNoRows {
				custAccount, err := isv.GetCustAccountByAppId(msg.AppId)
				if err != nil {
				   beego.Debug(err.Error())
				   return err
				}
				rslt, err := oauth.GetUserInfo2(custAccount.AccessToken, msg.FromUserName)
				if err != nil {
				   beego.Debug(err.Error())
				   return err
				}
				if userJSON, err := json.Marshal(rslt); err == nil {
		            beego.Debug("userJSON", string(userJSON))
                }
				if _, err = member.CreateWeChatMember(msg.AppId, rslt.Unionid, rslt, 0); err != nil {
				    beego.Debug(err.Error())
				}
			}
			if members, err := member.GetMemberByOpenId(msg.FromUserName); err == nil {
				if len(members.Unionid) < 5 {
				    custAccount, err := isv.GetCustAccountByAppId(msg.AppId)
					if err != nil {
					   beego.Debug(err.Error())
					   return err
					}
					rslt, err := oauth.GetUserInfo2(custAccount.AccessToken, msg.FromUserName)
					if err != nil {
					   beego.Debug(err.Error())
					   return err
					}
					if userJSON, err := json.Marshal(rslt); err == nil {
						beego.Debug("userJSON", string(userJSON))
					}
					members.Unionid = rslt.Unionid
					if err = member.UpdateMemberByOpenId(members, "unionid"); err != nil {
						beego.Debug(err.Error())
					}
				}
				if !members.IsSubScribe {
				    members.IsSubScribe = true
					if err := member.UpdateMemberByOpenId(members, "is_subscribe"); err != nil {
						beego.Debug(err.Error())
					}
				}
				cacheKey := fmt.Sprintf("%s%d", members.Unionid, 1100)
			    beego.Debug("redis set cacheKey:", cacheKey)
				if _, err = redisconn.Set(cacheKey, eventKey, 10*60); err == nil {
			        if custAccount, err := isv.GetCustAccountByAppId(msg.AppId); err == nil {
					   miniapp.SendTextMessage(custAccount.AccessToken,msg.FromUserName,"恭喜! 安全校验已通过! 你可以正常使用大黄蜂小程序了！")
					}
			    }else{
				    beego.Debug("SETEX", err.Error())
				}
			}else{
			    beego.Debug("appid", msg.AppId, "openid", msg.FromUserName, "GetMemberByOpenId no record")
			}
		}
	}
	return nil
}
